package com.dzsw.mail;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Properties;

public class JavaxMail162Example {

    public static void main(String[] args) throws GeneralSecurityException {
        sendMail0();
    }

    private static void sendMail0() throws GeneralSecurityException {
        // 邮件服务器配置
        String host = "smtp.exmail.qq.com";
        final String user = "sunzhe@sy-binal.com"; // 发件人邮箱
        final String password = "LmUmTJ7bjZdbjRXy"; // 发件人密码
        // 收件人邮箱
        String to = "sunzhe@sy-binal.com";
        // 配置属性
        Properties props = new Properties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.ssl.enable", "true");
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        props.put("mail.smtp.ssl.socketFactory", sf);
        // 获取默认session对象
        Session session = Session.getInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(user, password);
            }
        });
        try {
            // 创建邮件对象
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(user));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
            message.setSubject("Test Mail from Java");
            message.setText("Hello, this is a test mail from Java program!");
            // 发送邮件
            Transport.send(message);
            System.out.println("Mail sent successfully!");
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}
